<template>
  <div class="inventory-analysis">
    <!-- 页面标题 -->
    <PageHeader 
      title="库存分析" 
      description="查看和分析库存数据，包括库存趋势、周转率、滞销品分析等"
      icon="DataAnalysis"
    />
    
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalValue?.toLocaleString() || '0' }}</div>
            <div class="stat-label">库存总价值</div>
            <div class="stat-trend" :class="getTrendClass(stats.valueTrend)">
              <el-icon v-if="stats.valueTrend && stats.valueTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.valueTrend && stats.valueTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.valueTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalItems || '0' }}</div>
            <div class="stat-label">库存总数量</div>
            <div class="stat-trend" :class="getTrendClass(stats.itemTrend)">
              <el-icon v-if="stats.itemTrend && stats.itemTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.itemTrend && stats.itemTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.itemTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.turnoverRate || '0' }}%</div>
            <div class="stat-label">库存周转率</div>
            <div class="stat-trend" :class="getTrendClass(stats.turnoverTrend)">
              <el-icon v-if="stats.turnoverTrend && stats.turnoverTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.turnoverTrend && stats.turnoverTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.turnoverTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-value">{{ stats.outOfStockItems || '0' }}</div>
            <div class="stat-label">缺货商品数</div>
            <div class="stat-trend" :class="getTrendClass(-(stats.outOfStockTrend || 0))">
              <el-icon v-if="stats.outOfStockTrend && stats.outOfStockTrend > 0">
                <Top />
              </el-icon>
              <el-icon v-else-if="stats.outOfStockTrend && stats.outOfStockTrend < 0">
                <Bottom />
              </el-icon>
              {{ Math.abs(stats.outOfStockTrend || 0) }}% 同比
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="16">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>库存价值趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="valueTrendChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>库存分类占比</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="categoryPieChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 库存分析 -->
    <el-row :gutter="20" class="analysis-section">
      <el-col :span="12">
        <el-card class="analysis-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>滞销商品分析</span>
            </div>
          </template>
          <el-table :data="slowMovingItems" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="category" label="分类" />
            <el-table-column prop="stock" label="库存数量" />
            <el-table-column prop="daysInStock" label="库存天数" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="analysis-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>热销商品分析</span>
            </div>
          </template>
          <el-table :data="fastMovingItems" style="width: 100%">
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="category" label="分类" />
            <el-table-column prop="sold" label="销售数量" />
            <el-table-column prop="turnoverDays" label="周转天数" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { Top, Bottom } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据模型
interface InventoryStats {
  totalValue: number
  totalItems: number
  turnoverRate: number
  outOfStockItems: number
  valueTrend: number
  itemTrend: number
  turnoverTrend: number
  outOfStockTrend: number
}

interface InventoryItem {
  id: number
  name: string
  category: string
  stock: number
  daysInStock: number
  sold: number
  turnoverDays: number
}

// 响应式数据
const stats = reactive<InventoryStats>({
  totalValue: 0,
  totalItems: 0,
  turnoverRate: 0,
  outOfStockItems: 0,
  valueTrend: 0,
  itemTrend: 0,
  turnoverTrend: 0,
  outOfStockTrend: 0
})

const slowMovingItems = ref<InventoryItem[]>([])
const fastMovingItems = ref<InventoryItem[]>([])

// 图表引用
const valueTrendChart = ref<HTMLDivElement | null>(null)
const categoryPieChart = ref<HTMLDivElement | null>(null)
let valueTrendChartInstance: echarts.ECharts | null = null
let categoryPieChartInstance: echarts.ECharts | null = null

// 获取趋势类名
const getTrendClass = (trend: number | undefined) => {
  if (trend === undefined) return ''
  return trend > 0 ? 'trend-up' : trend < 0 ? 'trend-down' : ''
}

// 加载统计数据
const loadStats = () => {
  // 模拟数据
  stats.totalValue = 1850000
  stats.totalItems = 24500
  stats.turnoverRate = 6.8
  stats.outOfStockItems = 12
  stats.valueTrend = -2.5
  stats.itemTrend = 1.8
  stats.turnoverTrend = 0.5
  stats.outOfStockTrend = -15.2
}

// 加载分析数据
const loadAnalysisData = () => {
  // 模拟数据
  slowMovingItems.value = [
    { id: 1, name: '老款智能手机', category: '电子产品', stock: 1200, daysInStock: 180, sold: 50, turnoverDays: 360 },
    { id: 2, name: '过季服装', category: '服装', stock: 850, daysInStock: 150, sold: 30, turnoverDays: 420 },
    { id: 3, name: '旧版软件', category: '软件', stock: 320, daysInStock: 200, sold: 20, turnoverDays: 500 },
    { id: 4, name: '停产配件', category: '配件', stock: 180, daysInStock: 250, sold: 10, turnoverDays: 600 },
    { id: 5, name: '滞销图书', category: '图书', stock: 450, daysInStock: 120, sold: 25, turnoverDays: 380 }
  ]
  
  fastMovingItems.value = [
    { id: 1, name: '新款智能手机', category: '电子产品', stock: 500, daysInStock: 30, sold: 1200, turnoverDays: 15 },
    { id: 2, name: '热销服装', category: '服装', stock: 300, daysInStock: 20, sold: 850, turnoverDays: 12 },
    { id: 3, name: '流行配件', category: '配件', stock: 200, daysInStock: 25, sold: 680, turnoverDays: 18 },
    { id: 4, name: '畅销图书', category: '图书', stock: 150, daysInStock: 40, sold: 420, turnoverDays: 25 },
    { id: 5, name: '热门软件', category: '软件', stock: 100, daysInStock: 35, sold: 320, turnoverDays: 20 }
  ]
}

// 初始化价值趋势图表
const initValueTrendChart = () => {
  if (!valueTrendChart.value) return
  
  valueTrendChartInstance = echarts.init(valueTrendChart.value as unknown as HTMLElement)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
      }
    },
    series: [{
      data: [2000000, 1950000, 1900000, 1880000, 1850000, 1820000, 1800000, 1780000, 1750000, 1720000, 1700000, 1680000],
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      lineStyle: {
        width: 3
      }
    }]
  }
  
  valueTrendChartInstance.setOption(option)
}

// 初始化分类饼图
const initCategoryPieChart = () => {
  if (!categoryPieChart.value) return
  
  categoryPieChartInstance = echarts.init(categoryPieChart.value as unknown as HTMLElement)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '0%',
      left: 'center'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 35, name: '电子产品' },
        { value: 25, name: '服装' },
        { value: 15, name: '配件' },
        { value: 12, name: '图书' },
        { value: 8, name: '软件' },
        { value: 5, name: '其他' }
      ]
    }]
  }
  
  categoryPieChartInstance.setOption(option)
}

// 窗口大小改变时重置图表
const handleResize = () => {
  if (valueTrendChartInstance) {
    valueTrendChartInstance.resize()
  }
  if (categoryPieChartInstance) {
    categoryPieChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  loadStats()
  loadAnalysisData()
  initValueTrendChart()
  initCategoryPieChart()
  
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.inventory-analysis {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1f2d3d;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.trend-up {
  color: #52c41a;
}

.trend-down {
  color: #f5222d;
}

.charts-section,
.analysis-section {
  margin-bottom: 20px;
}

.chart-card,
.analysis-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px 0;
}

.chart {
  width: 100%;
}
</style>